package com.ciwong.epaper.modules.epaper.ui.html;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.epaper.ui.MyWebViewClient;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.toast.ZToast;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;
import com.ciwong.mobilelib.widget.BottomMenuDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:发布打卡作业页面
 * @author: wyk
 * @time: 2021/6/22 10:05
 */
public class AiHtmlActivity extends BaseHtmlActicity implements View.OnClickListener {

    private BridgeWebView bridgeWebView;

    private final int CODE_REQUEST_ALBUM_PERMISSION = 9900;
    private final int CODE_REQUEST_CAMERA_PERMISSION = 9901;

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private int videoOrPhoto = 1;
    private int imgCount;
    /**
     * 跳转码，相册
     */
    public static final int REQUEST_CODE_ALBUM = 0x0000012;
    /**
     * 跳转码，拍照
     */
    public static final int REQUEST_CODE_CAMERA = 0x0000011;

    /**
     * 跳转码，录像
     */
    public static final int ACTION_VIDEO_CAPTURE = 0x0000013;
    /**
     * 跳转码选择视频
     */
    public static final int REQUEST_VIDEO_CODE = 0x0000014;

    //跳转作业列表
    public static final int JUMP_SORECE_TYPE_ME_SETTING = 102;

    private final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;
    protected Mp3Recorder mp3Recorder;
    protected boolean isRecordFail = false;
    private double mVolume = -1.0;
    private boolean isRecord = false;
    //从相册选择照片集合
    List<Uri> PhotoResult = new ArrayList<>();

    private Uri submitVideoUri;

    private File tempPictureFile;

    private String tempMusicPath = "";
    //视频地址
    private File videoFile;
    //上传视频地址
    private String subVideoPath = "";
    private final static String TAG_VIDEO = "tag_video";
    private final static String TAG_IMAGE = "tag_image";
    private final static String TAG_AUDIO = "chatAi";
    private Uri photoUri;
    private String subImgPath;
    private ImageView img_stop_recording;
    private FrameLayout dk_work_frame;
    private List<String> subPicList = new ArrayList<>();
    private FrameLayout video_view;
    /**
     * 上传图片uri集合
     */
    private List<String> uriList = new ArrayList<>();

    private boolean isUpdateRecord = false;

    /**
     * 弹框
     */
    private BottomMenuDialog bottomMenuDialog;
    private File cutImgFile;

    @Override
    protected int setView() {
        return R.layout.activity_publish_dk_work;
    }

    @Override
    protected void findViews() {
        bridgeWebView = findViewById(R.id.publish_dk_webview);
        dk_work_frame = findViewById(R.id.dk_work_frame);
        video_view = findViewById(R.id.video_view);
    }

    @Override
    protected void initEvent() {

    }

    public void getUpdateRecordPath() {
        bridgeWebView.callHandler("getUpdateRecordPath", tempMusicPath, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                Log.e("callUpdateRecord","getUpdateRecordPath");
            }
        });
    }


    @Override
    public void finish() {
        if (null != bridgeWebView && bridgeWebView.canGoBack()) {
            bridgeWebView.goBack();// 返回前一个页面
        } else {
            super.finish();
        }
    }


    @Override
    protected void init() {
        setValideSource(false);
        hideTitleBar();
        bridgeWebView.setDefaultHandler(new DefaultHandler());
        bridgeWebView.setWebChromeClient(new MyWebChromeClient());
        String url = getUrl();
        Log.d(TAG, url);
        WebSettings webSettings = bridgeWebView.getSettings();
        webSettings.setAllowContentAccess(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        bridgeWebView.postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean isHavePermiss = XXPermissionTool.isHasPermission(AiHtmlActivity.this, Manifest.permission.RECORD_AUDIO);
                if (!isHavePermiss){
                    if (getRecordPermissDialog == null) {
                        getRecordPermissDialog = new CWDialog(AiHtmlActivity.this);
                        getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                        getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                        getRecordPermissDialog.setMessage(getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                        getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getRecordPermissDialog.dismiss();
                                if (Build.VERSION.SDK_INT >= 23 && getApplicationInfo().targetSdkVersion >= 23) {
                                    List<String> permissionList = new ArrayList<String>();
                                    Map<String, String> noteMap = new HashMap<>();
                                    permissionList.add(Manifest.permission.RECORD_AUDIO);
                                    noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
                                    XXPermissionTool.checkPermissions(AiHtmlActivity.this, //
                                            permissionList, //
                                            noteMap, //
                                            CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                                            new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                                                @Override
                                                public void onCheckPermissionsFinished(int flag) {
                                                    if (0 == flag) {

                                                    } else {

                                                    }
                                                }
                                            });
                                }
                            }
                        });
                        getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getRecordPermissDialog.dismiss();
                            }
                        });
                    }
                }
        }
        },1000);

        bridgeWebView.loadUrl(url);
        //通知上传照片
        bridgeWebView.registerHandler("webStartRecord", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                CWLog.e("webStartRecord =","webStartRecord");
                isUpdateRecord = false;
                showgetRecordPermissDialog();
            }
        });

        bridgeWebView.registerHandler("goBack", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                CWLog.e("registerHandler goBack =","goBack");
                finishActivity();
            }
        });


        bridgeWebView.registerHandler("webStopRecord", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                CWLog.e("webStopRecord =","webStopRecord");
                isUpdateRecord = true;
                stopRecord();
            }
        });


        bridgeWebView.registerHandler("webCancelRecord", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                CWLog.e("webStopRecord =","webStopRecord");
                isUpdateRecord = false;
                stopRecord();
            }
        });


        bridgeWebView.callHandler("getUpdateRecordPath", tempMusicPath, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                Log.e("callUpdateRecord","getUpdateRecordPath");
            }
        });

        ALiYunManager.getInstance().registerListener(aLiYunListener);

    }


    //获取跳转地址
    public String getUrl() {
        String url = "";
        bridgeWebView.setDefaultHandler(new DefaultHandler());
        bridgeWebView.setWebChromeClient(new WebChromeClient());
        url = "https://m.teacher.jiaofuyun.com/chatAi#/?origin=android&userId="+ EApplication.getInstance().getUserInfoBase().getUserId();
        return url;

    }

    //设置弹框 从相册选择 or 拍照
    private void setBottomMenuDialog() {
        bottomMenuDialog = new BottomMenuDialog(this);
        bottomMenuDialog
                .setBtnTextColor(getResources().getColor(R.color.color_light_green));
        bottomMenuDialog
                .setLastBtnTextColor(getResources().getColor(R.color.gray));

        ArrayList<String> str = new ArrayList<>();
        if (videoOrPhoto == 1) {
            str.add(getResources().getString(R.string.avatar_camera));
//            str.add(getResources().getString(R.string.avatar_photo));
            str.add(getResources().getString(android.R.string.cancel));
            bottomMenuDialog.setMenuTextList(str);
            ArrayList<View.OnClickListener> listeners = new ArrayList<>();

            listeners.add(new BottomClickListener1(0));
            listeners.add(new BottomClickListener1(1));
            bottomMenuDialog.setMenuOnClickListeners(listeners);
        } else {
            str.add(getResources().getString(R.string.avatar_video));
            str.add(getResources().getString(R.string.avatar_local_video));
            str.add(getResources().getString(android.R.string.cancel));
            bottomMenuDialog.setMenuTextList(str);

            ArrayList<View.OnClickListener> listeners = new ArrayList<>();

            listeners.add(new BottomClickListener(0));
            listeners.add(new BottomClickListener(1));
            listeners.add(new BottomClickListener(2));


            bottomMenuDialog.setMenuOnClickListeners(listeners);
        }


    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        /*if (id == R.id.img_stop_recording){
            stopRecord();
        }*/
    }

    class BottomClickListener1 extends ViewOnClickListener {
        private int index;

        public BottomClickListener1(int index) {
            this.index = index;
        }

        @Override
        public void avertRepeatOnClick(View v) {
            switch (index) {
                case 0:// 拍照
                    showgetCameraPermissDialog();
                    break;
                default:
                    break;
            }
            bottomMenuDialog.dismiss();
        }
    }

    class BottomClickListener extends ViewOnClickListener {
        private int index;

        public BottomClickListener(int index) {
            this.index = index;
        }

        @Override
        public void avertRepeatOnClick(View v) {
            switch (index) {
                case 0:// 拍照
                    showgetCameraPermissDialog();
                    break;
                case 1:// 从相册选
                    showgetAlbumPermissDialog();
                    break;
                default:
                    break;
            }
            bottomMenuDialog.dismiss();
        }
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        return true;
    }


    private CWDialog getAlbumPermissDialog;

    /**
     * 获取Album权限提示框
     */
    private boolean showgetAlbumPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            useAlbum();
        } else {
            if (getAlbumPermissDialog == null) {
                getAlbumPermissDialog = new CWDialog(this);
                getAlbumPermissDialog.setTitle(R.string.get_permiss_title);
                getAlbumPermissDialog.setTitleTextColor(Color.BLACK);
                getAlbumPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getAlbumPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                        useAlbum();
                    }
                });
                getAlbumPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                    }
                });
            }
            getAlbumPermissDialog.show();
        }
        return true;
    }


    /**
     * 使用相册，判断权限
     */
    private void useAlbum() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.READ_EXTERNAL_STORAGE, "读取相册权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_ALBUM_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                if (videoOrPhoto == 1) {
                                    BaseJumpManager.jumpToChoosePic(AiHtmlActivity.this, imgCount,
                                            REQUEST_CODE_ALBUM);
                                } else {
                                    BaseJumpManager.jumpToSysChooseVideoFile(AiHtmlActivity.this, REQUEST_VIDEO_CODE);
                                }

                            } else {
//                                showConfirmCommitDialog(MyInfoActivity, "未获取到读取相册权限，无法正常使用相册。");
                            }
                        }
                    });
        } else {
            BaseJumpManager.jumpToChoosePic(AiHtmlActivity.this, imgCount,
                    REQUEST_CODE_ALBUM);
        }
    }

    /**
     * 使用照相机，判断权限
     */
    private CWDialog getRecordPermissDialog;

    /**
     * 获取Record权限提示框
     */
    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(this);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }


    /**
     * 使用录音，判断权限
     */
    private boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                record();
                            } else {

                                // showConfirmCommitDialog(getActivity(),
                                // "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            record();
        }
        return true;
    }

    private Handler aliyunHandler = new Handler(Looper.getMainLooper());

    private Runnable getUpdateRecordPath = new Runnable() {
        @Override
        public void run() {
            getUpdateRecordPath();
        }
    };

    int countAliyun;

    /**
     * 监听上传
     */

    private Handler mRecorderHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }
            switch (msg.what) {
                case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                    /*img_micro_recording.setVisibility(View.VISIBLE);
                    Drawable drawable = img_micro_recording.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable).start();
                    }
*/
                    break;
                case Mp3Recorder.MSG_DB:// 录音分贝
                    Bundle b = msg.getData();
//                    Log.d(TAG, "###########Mp3Recorder.MSG_DB############" + Mp3Recorder.MSG_DB);
                    if (b != null) {
                        double db = b.getDouble("db");
                        if (db >= 0) {
                            Log.d(TAG, "###########db############" + db);
                            mVolume = db;
                        }
//                        Log.d(TAG, "###########db############" + db);

//                        if (microRecording != null && !Double.isNaN(db)) {
//                            microRecording.setRms(db);
//                        }
                    }
                    break;
                case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_AUDIO_RECORD############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);
                    DialogUtil.showSettingPermissions(AiHtmlActivity.this);
                    break;

                case Mp3Recorder.MSG_ERROR_REC_START:
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_REC_START############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);

                    DialogUtil.showSettingPermissions(AiHtmlActivity.this);
                    break;
                case Mp3Recorder.MSG_REC_STOPPED:// 录音结束
                    /*img_micro_recording.setVisibility(View.GONE);
                    Drawable drawable2 = img_micro_recording.getDrawable();
                    if (drawable2 != null && drawable2 instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable2).stop();
                    }*/

                    if (null != tempMusicPath && !"".equals(tempMusicPath)) {
                        addResult();
                    }


                    break;
                default:
                    break;
            }
        }

    };
    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {

        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {
            if (tag != null) {
                Log.d("byou", "aLiYunListener:onProgress" + tag + currentSize + "--totalSize:" + totalSize);
//                try {
//                    String photoPath = tag.toString();
//                    if (TAG_VIDEO.equals(photoPath)) {
//                        if (currentSize > 0 && totalSize > 0) {
//                            long progress = currentSize * 100 / totalSize;
//                            if (progress < 100) {
////                                updateDownloadProgress((int) progress);
//                            }
//                        }
//                    } else if (TAG_IMAGE.equals(photoPath)) {
//                        if (currentSize > 0 && totalSize > 0) {
//                            long progress = currentSize * 100 / totalSize;
//                            if (progress < 100) {
//                                updateDownloadProgress((int) progress);
//                            }
//                        }
//                    } else if (TAG_AUDIO.equals(photoPath)) {
//                        if (currentSize > 0 && totalSize > 0) {
//                            long progress = currentSize * 100 / totalSize;
//                            if (progress < 100) {
//                                updateDownloadProgress((int) progress);
//                            }
//                        }
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        }


        @Override
        public void onSuccess(Object tag, String url) {
            if (tag != null) {
                Log.d("byou", "aLiYunListener:onSuccess" + tag + "--url:" + url);
                tempMusicPath = url;
                try {
                    hideDownloadProgress();
                    Log.d(TAG, "###########Mp3Recorder.MSG_REC_STOPPED############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);
                    if (isUpdateRecord){
                        bridgeWebView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                bridgeWebView.callHandler("getUpdateRecordPath", tempMusicPath, new CallBackFunction() {
                                    @Override
                                    public void onCallBack(String data) {
                                        Log.e("callUpdateRecord","getUpdateRecordPath");
                                    }
                                });
                            }
                        },10);
                    }

//                    String photoPath = tag.toString();
//                    if (TAG_VIDEO.equals(photoPath)) {
//                        aliyunVideoUri = url;
//                        // 上传成功
//                        //hideDownloadHorizontalProgressBar();
//
//                    } else if (TAG_IMAGE.equals(photoPath)) {
//                        countAliyun++;
//                        alyunPicUriList.add(url);
//                        if (countAliyun == PhotoResult.size()) {
//                            countAliyun = 0;
//                            aliyunHandler.post(getUpdateImagePath);
//                        }
//                        //dkAnswer.setPictures(path);
//                    } else if (TAG_AUDIO.equals(photoPath)) {
//                        aliyunAudioUri = url;
//                        aliyunHandler.post(getUpdateRecordPath);
//                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
                try {
                    String photoPath = String.valueOf(tag);
                    if (photoPath.equals(tempMusicPath)) {
                        hideDownloadProgress();
                        ZToast.makeText(AiHtmlActivity.this,
                                "上传失败，请稍后重试！", ZToast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    };

    /**
     * 开始录音
     */
    public void startRecord() {
        tempMusicPath = ESystem.getMusicCacheDir(AiHtmlActivity.this, ESystem.getCacheFileName("ai_spoken", "mp3")).getAbsolutePath();
        Log.d("byou", "tempMusicPath=" + tempMusicPath);
        mp3Recorder = new Mp3Recorder(tempMusicPath, BaseConstants.SAMPLERATE, mRecorderHandler);
        mp3Recorder.start();
    }

    private Handler handler = new Handler(Looper.getMainLooper());

    private Runnable stopRecordRunnable = new Runnable() {
        public void run() {
            stopRecord();
        }
    };

    /**
     * /** 停止录音
     */
    public void stopRecord() {
        handler.removeCallbacks(stopRecordRunnable);
        if (null != recordBottomDialog) {
            recordBottomDialog.dismiss();
        }
        stopRecordView();
        //iEvaluateEngine.stop();
        try {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }

        } catch (RuntimeException e) {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }

            File file = new File(tempMusicPath);
            if (file.exists())
                file.delete();
        }

    }

    private Dialog recordBottomDialog;
    private PlayStateView publish_dk_audio_stateView;
    private TextView dk_audio_complete;

    //显示录音弹框
    private void showRecordBottomDialog() {
        recordBottomDialog = new Dialog(AiHtmlActivity.this, R.style.BottomDialog);
        View inflate = LayoutInflater.from(AiHtmlActivity.this).inflate(R.layout.activity_record_bottom_dialog, null);
        publish_dk_audio_stateView = inflate.findViewById(R.id.publish_dk_audio_stateView);
        dk_audio_complete = inflate.findViewById(R.id.dk_audio_complete);
        img_stop_recording = publish_dk_audio_stateView.findViewById(R.id.img_stop_recording);
        recordBottomDialog.setContentView(inflate);
        Window window = recordBottomDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        ViewGroup.LayoutParams layoutParams = inflate.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels / 5;
        inflate.setLayoutParams(layoutParams);
        //设置录音图标是显示状态
        publish_dk_audio_stateView.setDKAutoRecordState(true);

        img_stop_recording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopRecord();
            }
        });

        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        window.setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        window.getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    tempMusicPath = "";
                    stopRecord();
                }
                return true;
            }
        });

        publish_dk_audio_stateView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showgetRecordPermissDialog();
            }
        });

        dk_audio_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tempMusicPath = "";
                stopRecord();
            }
        });
        recordBottomDialog.show();

    }

    public void stopRecordView() {
        /*user_dk_audio_StateView_lay.setVisibility(View.GONE);
        dk_result_submit.setVisibility(View.VISIBLE);*/
        //user_dk_audio_img.stopOnlyRecord();
    }


    /**
     * 录音
     */
    protected void record() {
        // 开始录音
        try {
//            publish_dk_audio_stateView.setTimeCount(180000l);
//            publish_dk_audio_stateView.startUnAutoRecord();
            startRecord();
            // 开始线程，停止录音
            handler.postDelayed(stopRecordRunnable, 180000
            );
        } catch (OutOfMemoryError error) {
            isRecord = false;
            error.getStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        if (null != bridgeWebView) {
            bridgeWebView.destroy();
        }
        mRecorderHandler.removeCallbacksAndMessages(null);
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
        super.onDestroy();
    }

    private String downloadMsg = "";

    /**
     * 上传视频到阿里云
     */
    private final void submitVideo() {
        File localMixDubVideoFile = new File(subVideoPath);
        if (localMixDubVideoFile.exists()) {
            downloadMsg = "上传中，请稍等...";
            showDownloadProgress(downloadMsg);
            String VideoUrlKey = ALiYunManager.getInstance().getAIKey(subVideoPath);
            ALiYunManager.getInstance().addDKFile(subVideoPath,
                    VideoUrlKey, TAG_VIDEO);
        } else {
            ZToast.makeText(AiHtmlActivity.this, "视频不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }

    }

    /**
     * 上传图片到阿里云
     */
    private final void submitPic(String uri) {
        File localImgFile = new File(uri);
        if (localImgFile.exists()) {
            downloadMsg = "上传中，请稍等...";
            showDownloadProgress(downloadMsg);
            String photoUrlKey = ALiYunManager.getInstance()
                    .getAIKey(uri);
            ALiYunManager.getInstance().addDKFile(uri, photoUrlKey,
                    TAG_IMAGE);
        } else {
            ZToast.makeText(AiHtmlActivity.this, "图片不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }

    }

    /**
     * 上传音频
     *
     * @param
     * @param
     */
    public final void addResult() {
        File localImgFile = new File(tempMusicPath);
        if (localImgFile.exists()) {
//            downloadMsg = "上传中，请稍等...";
//            showDownloadProgress(downloadMsg);
            String photoUrlKey = ALiYunManager.getInstance()
                    .getAIKey(tempMusicPath);
            ALiYunManager.getInstance().addDKFile(tempMusicPath, photoUrlKey,
                    TAG_AUDIO);
            CWLog.d("aliyun", "提交" + System.currentTimeMillis() + "tag="
                    + tempMusicPath);
        } else {
            ZToast.makeText(AiHtmlActivity.this, "音频不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Uri outPuturi;
            Intent intent = new Intent();
            switch (requestCode) {
                case REQUEST_VIDEO_CODE:
                    if (data != null) {
                        submitVideoUri = data.getData();
                        subVideoPath = getPath(this, submitVideoUri);
                        submitVideo();
                    }
                    break;
                case REQUEST_CODE_CAMERA:
                    photoUri = FileProvider7.getUriForFile(this, tempPictureFile);
                    PhotoResult.clear();
                    PhotoResult.add(photoUri);
                    if (photoUri != null) {
                        subImgPath = tempPictureFile.getPath();
                        subPicList.add(subImgPath);
                        uriList.add(photoUri.toString());
                    }
                    submitPic(subImgPath);
                    break;
                case REQUEST_CODE_ALBUM:
//                    if (data != null) {
//                        if (videoOrPhoto == 1) {
//                            PhotoResult = Matisse.obtainResult(data);
//                            for (int i = 0; i < PhotoResult.size(); i++) {
//                                Uri path = PhotoResult.get(i);
//                                String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                                Cursor cursor = getContentResolver().query(path,
//                                        filePathColumn, null, null, null);
//                                cursor.moveToFirst();
//                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                                subImgPath = cursor.getString(columnIndex);
//                                submitPic(subImgPath);
//                                subPicList.add(subImgPath);
//                                uriList.add(path.toString());
//                                cursor.close();
//                            }
//                        } else {
//                            submitVideoUri = data.getData();
//                            String[] filePathColumn = {MediaStore.Video.Media.DATA};
//
//                            Cursor cursor = getContentResolver().query(submitVideoUri,
//                                    filePathColumn, null, null, null);
//                            cursor.moveToFirst();
//
//                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                            subVideoPath = cursor.getString(columnIndex);
//                            cursor.close();
//                            submitVideo();
//                        }
//                    }
                    break;

                case ACTION_VIDEO_CAPTURE:
                    if (data != null) {
                        submitVideoUri = data.getData();
                        String[] filePathColumn = {MediaStore.Video.Media.DATA};

                        Cursor cursor = getContentResolver().query(submitVideoUri,
                                filePathColumn, null, null, null);
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        subVideoPath = cursor.getString(columnIndex);
                        cursor.close();
                        submitVideo();
                        //user_dk_video_submit.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
                    }
                    break;

                case CODE_REQUEST_CAMERA_PERMISSION:
                    if (XXPermissionTool.isHasPermission(AiHtmlActivity.this, Manifest.permission.CAMERA)) {
                        tempPictureFile = ESystem.getPicturesCacheDir(AiHtmlActivity.this, ESystem.getCacheFileName("dkwork", "jpg"));
                        BaseJumpManager.jumpToSysCamera(AiHtmlActivity.this,
                                tempPictureFile, REQUEST_CODE_CAMERA);
                    }
                    break;

                default:
                    break;
            }
        }
    }


    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    @Override
    protected void loadData() {

    }

    class MyWebChromeClient extends WebChromeClient {
        private View myView = null;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        // 全屏
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
//            ViewGroup parent = (ViewGroup) bridgeWebView.getParent();
//            parent.removeView(bridgeWebView);
//
//            video_view.addView(view);
//            video_view.setVisibility(View.VISIBLE);
            myView = view;
            setFullScreen();
        }

        // 退出全屏
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
            if (myView != null) {
                video_view.removeAllViews();
                dk_work_frame.addView(bridgeWebView);
                video_view.setVisibility(View.GONE);

                myView = null;
                quitFullScreen();
            }
        }
    }

    /**
     * 设置全屏
     */
    private void setFullScreen() {
        // 设置全屏的相关属性，获取当前的屏幕状态，然后设置全屏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 退出全屏
     */
    private void quitFullScreen() {
        // 声明当前屏幕状态的参数并获取
        final WindowManager.LayoutParams attrs = this.getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().setAttributes(attrs);
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

}
